package su.jet.irc.server.service;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import su.jet.common.irc.domain.Message;
import su.jet.common.irc.domain.User;
import su.jet.irc.datagateway.DataAccess;
import su.jet.irc.server.domain.ChatServer;


public class DataService {
	
	private DataAccess chatDao;
		
	public DataService(DataAccess chatDao) {
		this.chatDao = chatDao;
	}

	public Set<User> loadRegisteredUsersFromDB() {
		try {
			return chatDao.getUsers();
		} catch (SQLException e) {
			System.out.println("data load error");
			e.printStackTrace();
		}
		return null;
	}
	
	@SuppressWarnings({ "unchecked" })
	public Set<User> loadRegisteredUsersFromFile(String fileName) throws ClassNotFoundException, IOException {
		Set<User> regUsers;
		FileInputStream fileInputStream = null;
		ObjectInputStream objectInputStream = null;
		try {
			fileInputStream = new FileInputStream(fileName);
			objectInputStream = new ObjectInputStream(fileInputStream);
			Object inputObj = objectInputStream.readObject();
			regUsers = (Set<User>)inputObj;
			return regUsers;
		} 
		finally {
			if (objectInputStream != null)
				objectInputStream.close();
			if (fileInputStream != null)
				fileInputStream.close();
		}
	}
	
	public void addMessageToHistory(Message message, Timestamp timestamp){
		chatDao.addMessage(message, timestamp);
	}
	
	@SuppressWarnings({ "unchecked", "deprecation", "rawtypes" })
	public List<String> getHistoryFromPeriod(User user, int period) {
		List<String> history = new ArrayList<String>();
		Map<Message, Timestamp> messageMap;
		TreeMap<Message, Timestamp> sortedMessagesMap;
		try {
			messageMap = chatDao.getMessagesFromPeriod(user, period);
			
			sortedMessagesMap = new TreeMap(new ValueComparator(messageMap));
			sortedMessagesMap.putAll(messageMap);
			for (Message message : sortedMessagesMap.keySet()) {
				Timestamp date = messageMap.get(message);
				String dateAndTime = date.toLocaleString();
				
				String sender =	message.getSender().getNickName();
				String receiver = (message.getReceiver() == null) ? "All" : message.getReceiver().getNickName();
				String text = message.getText();
				
				String messageString = String.format("%s | %s -> %s : %s", dateAndTime, sender, receiver, text);
				history.add(messageString);
			}
		} catch (SQLException e) {
			System.out.println("data load error");
			e.printStackTrace();
		}
		return history;
	}

	public void addUserToDB(User user) {
		try {
			if (!ChatServer.registeredUsers.contains(user))
				chatDao.addUser(user);
			else
				System.out.println("user already exist");
		} catch (SQLException e) {
			System.out.println("error adding new user");
		}
		
	}
}

@SuppressWarnings("rawtypes")
class ValueComparator implements Comparator {

	  Map<Message, Timestamp> base;
	  public ValueComparator(Map<Message, Timestamp> base) {
	      this.base = base;
	  }

	  public int compare(Object a, Object b) {
		  if (base.get(a).getTime() > base.get(b).getTime()) {
			  return 1;
		  } else 
			  return -1;
     }
}
